#include "websocket_session.hpp"
#include <iostream>

/**
 * @brief WebSocketSession构造函数实现
 * 
 * 初始化WebSocket流和消息接收器
 * 将TCP套接字移动到WebSocket流中
 */
WebSocketSession::WebSocketSession(boost::asio::ip::tcp::socket socket, IMessageReceiver& receiver, uint32_t session_id)
    : ws_(std::move(socket)), receiver_(receiver), session_id_(session_id) {
}

/**
 * @brief 启动WebSocket会话
 * 
 * 开始WebSocket握手过程
 * 握手成功后开始读取消息
 */
void WebSocketSession::start() {
    ws_.async_accept(
        [self = shared_from_this()](boost::beast::error_code ec) {
            if (!ec) {
                self->do_read();  // 握手成功后开始读取消息
            }
        });
}

/**
 * @brief 开始读取消息
 * 
 * 异步等待新的WebSocket消息
 * 使用共享指针确保会话对象在异步操作期间保持存活
 */
void WebSocketSession::do_read() {
    ws_.async_read(
        buffer_,
        [self = shared_from_this()](boost::beast::error_code ec, std::size_t bytes_transferred) {
            self->on_read(ec, bytes_transferred);
        });
}

/**
 * @brief 发送消息
 * @param message 消息
 */
void WebSocketSession::send(const nlohmann::json& message) {
    ws_.async_write(boost::asio::buffer(message.dump()), [self = shared_from_this()](boost::beast::error_code ec, std::size_t bytes_transferred) {
        self->on_write(ec, bytes_transferred);
    });
}
/**
 * @brief 处理读取到的消息
 * 
 * 将接收到的消息转换为字符串
 * 通过消息接收器处理消息
 * 清空缓冲区并继续读取下一条消息
 */
void WebSocketSession::on_read(boost::beast::error_code ec, std::size_t bytes_transferred) {
    if (ec) {
        // Check if this is a normal closure
        if (ec == boost::beast::websocket::error::closed) {
            Logger::info("WebSocket connection closed normally");
        } else {
            Logger::error("Error reading from WebSocket: {}", ec.message());
        }
        return;
    }

    // 将接收到的消息转换为字符串
    std::string message = boost::beast::buffers_to_string(buffer_.data());
    std::vector<uint8_t> data(message.begin(), message.end());
    
    // 通过消息接收器处理消息
    
    receiver_.handle_message(data, session_id_);

    // 清空缓冲区
    buffer_.consume(buffer_.size());

    // 继续读取下一条消息
    do_read();
}

/**
 * @brief 处理写入完成
 * 
 * 处理消息发送完成后的回调
 * 目前仅记录错误信息
 */
void WebSocketSession::on_write(boost::beast::error_code ec, std::size_t bytes_transferred) {
    if (ec) {
        // Check if this is a normal closure
        if (ec == boost::beast::websocket::error::closed) {
            Logger::info("WebSocket connection closed normally during write");
        } else {
            Logger::error("Error writing to WebSocket: {}", ec.message());
        }
        return;
    }
} 